import { defineStore } from "pinia"
import { computed, ref } from "vue"
import { ElMessage } from 'element-plus';
import { useUserStore } from "./userStore";
import { getCartAPI } from "@/apis/cart"
import { findNewCartListAPI } from "@/apis/cart";
import { delCartAPI } from "@/apis/cart";

export const useCartStore = defineStore('cart', () => {
  // state
  const cartList = ref([])
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.data.result.token)
  // action
  //更新购物车
  const updateCart = async () => {
    const res = await findNewCartListAPI()
    cartList.value = res.data.result
  }
  // 添加购物车
  const addCart = async (goods) => {
    // 如果是已经登录了
    if (isLogin.value) {
      await getCartAPI(goods)
      updateCart()
    }
    else {
      const item = cartList.value.find(item => goods.skuId === item.skuId)
      if (item) item.count += goods.count
      else cartList.value.push(goods)
    }
    ElMessage.success('加入购物车成功！')
  }
  // 删除购物车
  const delCart = async (skuId) => {
    if (isLogin.value) {
      await delCartAPI([skuId])
      updateCart()
    }
    else {
      cartList.value = cartList.value.filter(item => item.skuId !== skuId)
    }
  }

  //清除购物车
  const clearCart = () => {
    cartList.value = []
  }

  const singleCheck = (selected, i) => {
    const item = cartList.value.find(item => item.skuId === i.skuId)
    item.selected = selected
  }
  const allCheck = (selected) => {
    cartList.value.forEach(item => item.selected = selected)
  }


  // 计算属性
  const allCount = computed(() => cartList.value.reduce((sum, item) => sum + item.count, 0))
  const allPrice = computed(() => cartList.value.reduce((sum, item) => sum + item.count * item.price, 0))
  const isAll = computed(() => cartList.value.every(item => item.selected))
  const selectCount = computed(() => cartList.value.filter(item => item.selected === true).reduce((sum, item) => sum + item.count, 0))
  const selectPrice = computed(() => cartList.value.filter(item => item.selected === true).reduce((sum, item) => sum + item.count * item.price, 0))
  return {
    cartList,
    addCart,
    delCart,
    allCount,
    allPrice,
    singleCheck,
    allCheck,
    isAll,
    selectCount,
    selectPrice,
    clearCart,
    updateCart
  }
},
  {
    persist: true
  }
)
